<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 搜索部分 -->
        <el-form ref="form" :inline="true" :model="query" label-width="80px" class="demo-form-inline">
          <el-row type="flex">
            <el-col :span="20">
              <el-form-item label="学科名称">
                <el-input
                  v-model="query.subjectName"
                  style="width: 280px"
                />
              </el-form-item>
              <el-form-item>
                <el-button @click="clearSub">清除</el-button>
                <el-button type="primary" @click="OnSearch">搜索</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="4" >
              <el-button type="success" @click="addSuject" icon="el-icon-edit">新增学科</el-button>
            </el-col>
          </el-row>
        </el-form>

        <!-- 新增学科弹框 -->
        <el-dialog
          :title="isEdit?'修改学科':'新增学科'"
          :visible.sync="showDialog"
          width="30%"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          @close="close"
        >
          <el-form
            ref="form"
            :model="form"
            :rules="rules"
            label-width="120px"
            style="padding: 0 30px 0 0px"
          >
            <el-form-item label="学科名称" prop="subjectName">
              <el-input
                v-model="form.subjectName"
                placeholder="请输入学科名称"
              />
            </el-form-item>
            <el-switch
              v-model="form.isFrontDisplay"
              active-color="#13ce66"
              inactive-color="#ff4949"
              inactive-text="是否显示"
            >
            </el-switch>
            <el-form-item style="text-align: right">
              <el-button @click="showDialog = false">取消</el-button>
              <el-button type="primary" @click="onSubmit">{{ isEdit ? '修改' : '添加' }}</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>

        <!-- 消息提示 -->
        <el-alert :title="cTitle" type="info" show-icon :closable="false">
        </el-alert>

        <!-- 表格 -->
        <el-table :data="list" style="width: 100%; margin: 20px 0 20px 0">
          <el-table-column type="index" label="序号" />
          <el-table-column prop="subjectName" label="学科名称" width="100"/>
          <el-table-column prop="username" label="创建者" width="120"/>
          <el-table-column label="创建日期" width="150">
            <template slot-scope="scope">
              {{ scope.row.addDate | formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="前台是否显示" width="120">
            <template slot-scope="scope">
              {{ scope.row.isFrontDisplay === 1 ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column prop="twoLevelDirectory" label="二级目录" />
          <el-table-column prop="tags" label="标签"  />
          <el-table-column prop="totals" label="题目数量" />
          <el-table-column prop="date" label="操作" width="250">
            <template slot-scope="scope">
              <el-button type="text" @click="$router.push('directorys?id='+scope.row.id+'&name='+scope.row.subjectName)">学科分类</el-button>
              <el-button type="text" @click="$router.push('tags?id='+scope.row.id+'&name='+scope.row.subjectName)">学科标签</el-button>
              <el-button type="text"  @click="detailSub(scope.row)">修改</el-button>
              <el-button type="text" @click="delSub(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.page"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="query.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-card>
    </div>
  </div>
</template>

<script>
import { list, add, remove, update } from '@/api/hmmm/subjects'
import dayjs from 'dayjs'

export default {
  name: 'Subject',
  data () {
    return {
      list: [], // 学科列表
      // 搜索数据
      form: {
        subjectName: '', // 关键字
        isFrontDisplay: true// 是否为开启状态
      },
      // 校验规则
      rules: {
        subjectName: [
          { required: true, message: '请输入学科名称', trigger: 'blur' }
        ]
      },
      total: 0, // 数据总条数
      query: {
        pagesize: 10, // 每页显示条数
        page: 1, // 当前页数
        subjectName: null // 学科名称
      },
      showDialog: false, // 是否展示弹框
      isEdit: false// 是否为编辑状态
    }
  },

  computed: {
    // 数据总条数
    cTitle () {
      return `数据一共${this.total}条`
    }
  },

  created () {
    // 调用获取列表的方法
    this.getlist()
  },

  filters: {
    //  格式化时间
    formatTime (value) {
      return dayjs(value).format('YYYY-MM-DD h:mm:ss')
    }
  },

  methods: {
    //   获取学科列表
    async getlist () {
      const res = await list(this.query)
      this.list = res.data.items
      // 数据总条数
      this.total = res.data.counts
    },

    //  每页显示条数发生改变时触发
    handleSizeChange (newPageSize) {
      this.query.pagesize = newPageSize
      this.getlist()
    },

    //  页码发生改变时触发
    handleCurrentChange (newPage) {
      this.query.page = newPage
      this.getlist()
    },

    // 搜索学科
    OnSearch () {
      this.query.page = 1
      this.getlist()
    },

    // 清除搜索
    clearSub () {
      this.query.subjectName = ''
      this.getlist()
    },

    //  新增学科
    addSuject () {
      // 展示弹框
      this.showDialog = true
      // 新增状态
      this.isEdit = false
    },

    //  确定添加/编辑学科
    onSubmit () {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        // 编辑状态
        if (this.isEdit) {
          const res = await update(this.form)
          // 失败提示
          if (!res.data.success) return this.$message.error('修改学科失败')
          // 成功提示
          this.$message.success('修改学科成功')
        } else {
        // 新增添加学科
          const res = await add(this.form)
          if (!res.data.status === 200 || res.data.statusText === 'OK') return this.$message.error('新增学科失败')
          this.$message.success('新增学科成功')
        }
        // 关闭弹框
        this.showDialog = false
        this.getlist()
      })
    },

    //  关闭弹框
    close () {
      // 清空表单
      this.form = {
        subjectName: '',
        isFrontDisplay: true,
        subId: ''
      }
      this.$refs.form.resetFields()
    },

    //  修改学科数据回显
    detailSub (row) {
      // 展示弹框,编辑状态,数据回显,传入id，判断禁用/开启状态
      this.showDialog = true
      this.isEdit = true
      this.form.subjectName = row.subjectName
      this.form.id = row.id
      if (row.isFrontDisplay === 1) {
        this.form.isFrontDisplay = true
      } else {
        this.form.isFrontDisplay = false
      }
    },

    //  学科删除
    async delSub (row) {
      const delRes = await this.$confirm('此操作将永久删除该学科, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (delRes === 'cancel') return this.$message.info('您取消了删除')
      // 传入id
      this.form.id = row.id
      const res = await remove(this.form)
      // 页码优化
      if (this.list.length === 1) {
        this.query.page--
        if (this.query.page <= 0) {
          this.query.page = 1
        }
      }
      // 失败提示，成功提示，更新列表
      if (!res.data.success) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getlist()
    }
  }
}
</script>

<style scoped>
.el-switch.is-checked {
    margin-left: 50px;
}
.el-col.el-col-4 {
    text-align: right;
}

.el-pagination {
  text-align: right;
}
</style>
